package acwing.dfs;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 献给阿尔吉侬的花束
 *
 * @author yang
 * @date 2021/12/6
 */
public class 献给阿尔吉侬的花束 {

    static int N = 210;
    static int[][] dist = new int[N][N]; //记录最短距离
    static char[][] g = new char[N][N];
    static int[] dx = {-1,0,1,0};
    static int[] dy = {0,1,0,-1};
    static int n;
    static int m;
    static PIIs start;
    static PIIs end;

    public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(reader.readLine().trim());
        while (T-- > 0) {
            String[] s1 = reader.readLine().split(" ");
            n = Integer.parseInt(s1[0]);
            m = Integer.parseInt(s1[1]);
            for (int i = 0; i < n; i++) {
                char[] chars = reader.readLine().toCharArray();
                for (int j = 0; j < m; j++) {
                    g[i][j] = chars[j];
                    if (g[i][j] == 'S') start = new PIIs(i, j);
                    else if (g[i][j] == 'E') end = new PIIs(i, j);
                }
            }
            int t = bfs(start, end);
            if (t == -1) System.out.println("oop!");
            else System.out.println(t);
        }

    }

    private static int bfs(PIIs start, PIIs end) {

        Queue<PIIs> queue = new LinkedList<>();
        for (int i = 0; i < n; i++) Arrays.fill(dist[i], -1);
        dist[start.x][start.y] = 0;
        queue.add(start);
        while (!queue.isEmpty()) {
            PIIs t = queue.poll();
            for (int i = 0; i < 4; i++) {
                int x = t.x + dx[i];
                int y = t.y + dy[i];
                if (x < 0 || x >= n || y < 0 || y >= m) continue;
                if (g[x][y] == '#') continue;
                if (dist[x][y] != -1) continue;

                dist[x][y] = dist[t.x][t.y] + 1;
                if (x == end.x && y == end.y) return dist[x][y];

                queue.add(new PIIs(x,y));
            }
        }
        return -1;
    }
}
class PIIs{
    public int x;
    public int y;
    public PIIs(int x,int y)
    {
        this.x = x;
        this.y = y;
    }
}